package com.zeratul.web.advice;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.core.result.R;
import com.zeratul.common.trace.TraceIdManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 给响应对象添加全局追踪号
 */
@RestControllerAdvice
public class ResultDataHandler implements ResponseBodyAdvice {

    @Autowired
    private TraceIdManager traceIdManager;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (ObjectUtil.isNotNull(body) && body instanceof R<?> r) {
            r.setTraceId(traceIdManager.getTraceId());
        }
        return body;
    }
}
